<template>
  <div class="test-exam-topic">
    <el-form :inline="true" :model="formData" :rules="rules" ref="formData">
      <span class="title">当前试卷：{{ examName }}</span>
      <el-form-item label="测试卷名称" prop="topicName">
        <el-input
          v-model="formData.topicName"
          placeholder="请填写测试卷题目"
          autocomplete="off"
          :clearable="true"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
        <el-button type="primary" @click="dialogFormVisible = true"
          >添加试卷题目</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 添加试卷题目 -->
    <el-dialog
      title="添加试卷题目"
      width="38%"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
    >
      <el-form
        :model="insertForm"
        :rules="insertRules"
        ref="insertForm"
        class="insertForm"
      >
        <el-form-item
          label="测试题目"
          :label-width="formLabelWidth"
          prop="topicName"
        >
          <el-input
            type="textarea"
            :rows="4"
            v-model="insertForm.topicName"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="选项A"
          :label-width="formLabelWidth"
          prop="topicOptionA"
        >
          <el-input
            v-model="insertForm.topicOptionA"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="选项B"
          :label-width="formLabelWidth"
          prop="topicOptionB"
        >
          <el-input
            v-model="insertForm.topicOptionB"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="选项C"
          :label-width="formLabelWidth"
          prop="topicOptionC"
        >
          <el-input
            v-model="insertForm.topicOptionC"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="选项D"
          :label-width="formLabelWidth"
          prop="topicOptionD"
        >
          <el-input
            v-model="insertForm.topicOptionD"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="正确选项"
          :label-width="formLabelWidth"
          prop="topicRightOption"
        >
          <el-input
            v-model="insertForm.topicRightOption"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="题目分值"
          :label-width="formLabelWidth"
          prop="topicScore"
        >
          <el-input
            v-model="insertForm.topicScore""
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="insert" :loading="insertLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
     <!-- 表格 -->
     <div class="admin-table">
      <div class="batch-btn">
        <el-button
          type="danger"
          size="mini"
          @click="batchDelete"
          v-show="this.multipleSelection.length > 0"
          >批量删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="46" align="center">
        </el-table-column>
        <el-table-column
          type="index"
          width="49"
          :index="indexConfig"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          label="试卷题目"
          prop="topicName"
          width="120"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="选项A"
          prop="topicOptionA"
          width="120"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="选项B"
          prop="topicOptionB"
          width="120"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="选项C"
          prop="topicOptionC"
          width="120"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="选项D"
          prop="topicOptionD"
          width="120"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="正确答案"
          prop="topicRightOption"
          width="50"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="题目分值"
          prop="topicScore"
          width="50"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column label="创建时间" width="120" align="center"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="120" align="center"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="edit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" size="mini" @click="del(scope.row)"
            >删除</el-button
          >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-show="tableData.length > 0"
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        :pager-count="7"
        style="text-align: right; margin-top: 24px"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getTestExamTopicList,
  insertTestExamTopic,
  batchDeleteTestExamTopic,
} from "@/api/admin/testExamTopic";
export default {
  name: "TestExamTopicView",
  data() {
    return {
      formData: {
        topicName: "",
        testExamId: "",
      },
      rules: {
        topicName: [
          { required: true, message: "请输入测试卷名称", trigger: "blur" },
        ],
      },
      insertForm: {
        testExamId: "",
        topicName: "",
        topicOptionA: "",
        topicOptionB: "",
        topicOptionC: "",
        topicOptionD: "",
        topicRightOption: "",
        topicScore: "",
      },
      insertRules: {
        topicName: [
          { required: true, message: "请输入题目名称", trigger: "blur" },
        ],
        topicOptionA: [
          { required: true, message: "请输入选项A", trigger: "blur" },
        ],
        topicOptionB: [
          { required: true, message: "请输入选项B", trigger: "blur" },
        ],
        topicOptionC: [
          { required: true, message: "请输入选项C", trigger: "blur" },
        ],
        topicOptionD: [
          { required: true, message: "请输入选项D", trigger: "blur" },
        ],
        topicRightOption: [
          { required: true, message: "请输入正确答案", trigger: "blur" },
          {
            pattern: /^[ABCD]$/,
            message: "请输入大写的ABCD",
            trigger: "blur",
          },
        ],
        topicScore: [
          { required: true, message: "请输入题目分数", trigger: "blur" },
        ],
      },
      page: 1,
      pageSize: 8,
      total: 0,
      currentPage: 1,
      dialogFormVisible: false,
      insertLoading: false,
      formLabelWidth: "120px",
      multipleSelection: [],
      tableData: [],
      tableLoading: false,
    };
  },
  props: ["examName", "id"],
  created() {
    this.insertForm.testExamId = this.id;
    this.formData.testExamId = this.id;
    this.getDataList();
  },
  methods: {
    // 自定义校验规则
    customValidator(rule, value, callback) {
      const { topicName } = this.formData;
      if (!topicName) {
        callback(new Error("请填写信息"));
      } else {
        callback();
      }
    },
    // 分页查询
    query() {
      this.$refs.formData.validate(async (v) => {
        if (v) {
          this.page = 1;
          this.getDataList();
        }
      });
    },
    // 清空新增表单
    clear() {
      this.page = 1;
      this.currentPage = 1;
      this.$refs.formData.resetFields();
      this.getDataList();
    },
    // 关闭新增对话框的操作
    closeDialog() {
      this.insertLoading = false;
      this.fileList = [];
      this.$refs.insertForm.resetFields();
    },
    // 新增
    insert() {
      this.$refs.insertForm.validate(async (v) => {
        if (v) {
          try {
            this.insertLoading = true;
            // 转换格式
            this.insertForm.topicName = this.insertForm.topicName
              .replace(/\r\n/g, "<br/>")
              .replace(/\n/g, "<br/>")
              .replace(/\s/g, " ");
            const res = await insertTestExamTopic(this.insertForm);
            this.dialogFormVisible = false;
            await this.getDataList();
          } finally {
            this.insertLoading = false;
          }
        }
      });
    },
    // 获取数据
    async getDataList() {
      try {
        this.tableLoading = true;
        const res = await getTestExamTopicList({
          ...this.formData,
          page: this.page,
          pageSize: this.pageSize,
        });
        this.tableData = res.data.records;
        this.total = res.data.total;
      } finally {
        this.tableLoading = false;
      }
    },
    // 配置表格索引
    indexConfig(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    // 当选项发生变化触发
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页查询
    handleCurrentChange(page) {
      this.page = page;
      this.currentPage = page;
      this.getDataList();
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 编辑
    edit(row) {
      // 可以依然跳转到layout中的router-view中
      this.$router.push({
        name: "AdminEditTestExamTopic",
        params: { id: row.id, testExamId: this.id, examName: this.examName },
      });
    },
    // 删除
    async del(row) {
      this.$confirm("确定删除所选数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await batchDeleteTestExamTopic([row.id]);
        await this.getDataList();
      });
    },
    // 批量删除
    async batchDelete() {
      const ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      this.$confirm("确定删除所选数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await batchDeleteTestExamTopic(ids);
        await this.getDataList();
      });
    },
  },
};
</script>

<style lang="less" scoped>
.test-exam-topic {
  width: 100%;
  height: 100%;
  background-color: #fff;
  .title {
    margin-right: 50px;
    line-height: 38px;
    font-size: 18px;
  }
  .insertForm {
    width: 440px;
  }
  .admin-table {
    .batch-btn {
      height: 28px;
      margin-bottom: 4px;
    }
  }
}

/*
解决单选框样式问题
  Blocked aria-hidden on an element because its descendant retained focus. 
  The focus must not be hidden from assistive technology users. 
  Avoid using aria-hidden on a focused element or its ancestor. 
  Consider using the inert attribute instead, which will also prevent focus. 
  For more details, see the aria-hidden section of the WAI-ARIA specification at Element with focus: input Ancestor with aria-hidden:
*/
/deep/ input[aria-hidden="true"] {
  display: none !important;
}
/deep/.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
</style>